﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinFormStore.通信层
{
    public class ScannerComLib
    {
        private SerialPort serialPort = new SerialPort();
        public void OpenCom(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits)
        {
            if (serialPort.IsOpen)
            {
                serialPort.Close();
            }
            serialPort.PortName = portName;
            serialPort.BaudRate = baudRate;
            serialPort.Parity = parity;
            serialPort.DataBits = dataBits;
            serialPort.StopBits = stopBits;
            serialPort.DataReceived += SerialPort_DataReceived;
            serialPort.Open();
        }
        public event Action<string> CodeReceived;//自定义事件
        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            //需要加一定的延时，否则可能会接收不完整
            Thread.Sleep(50);
            int count = this.serialPort.BytesToRead;
            if (count > 0)
            {
                byte[] data = new byte[count];
                this.serialPort.Read(data, 0, count);
                CodeReceived?.Invoke(Encoding.Default.GetString(data));
            }
        }
        public void CloseCom()
        {
            if (serialPort.IsOpen) { serialPort.Close(); }
        }
    }
}
